package com.examples.spider;

import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.utils.FilePersistentBase;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author : feilong.gao
 * email : feilong.gao.thebeastshop.com
 * date : 2021/2/18
 */
public class Convert extends FilePersistentBase {

    private static String CHAPTER_FILES = "chapter";
    private static String CONTENT_LINE_BREAK = "    ";
    private static String path = "D:/FaShiLu";
    private static String gitBookSummary = "SUMMARY.md";
    private static String outFileName = "法师路.md";

    private void gitBook2Markdown() {

        String outFile = path + FilePersistentBase.PATH_SEPERATOR + outFileName;
        String inSummaryFile = path + FilePersistentBase.PATH_SEPERATOR + gitBookSummary;
        try {
            BufferedReader summaryReader = new BufferedReader(new FileReader(getFile(inSummaryFile)));
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getFile(outFile), true), "UTF-8"));

            while (true) {
                String title = summaryReader.readLine();
                if (StringUtils.isBlank(title)) {
                    summaryReader.close();
                    printWriter.println();
                    printWriter.close();
                    break;         // 结束读取
                }
                String chapterPath = parseString(title, false);
                if (chapterPath.contains(CHAPTER_FILES)) {
                    String chapterFile = path + FilePersistentBase.PATH_SEPERATOR + chapterPath;
                    BufferedReader chapterReader = new BufferedReader(new FileReader(getFile(chapterFile)));
                    String chapterLine = "";
                    while (true) {
                        chapterLine = chapterReader.readLine();
                        if (StringUtils.isBlank(chapterLine)) {
                            chapterReader.close();
                            break;
                        }
                        printWriter.println(chapterLine);

                    }
                } else {
                    printWriter.println(title);
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Convert convert = new Convert();
        convert.gitBook2Markdown();
    }


    private String parseString(String source, Boolean isTitle) {
        String pattern = null;
        if (isTitle) {
            pattern = "(?<=\\[).*?(?=\\])";  //括号内内容为要提取的内容
        } else {
            pattern = "(?<=\\().*?(?=\\))";  //括号内内容为要提取的内容
        }
        Matcher m = Pattern.compile(pattern).matcher(source);
        return m.find() ? m.group() : "";
    }

}
